package com.nsi.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import com.nsi.common.Const;
import com.nsi.common.ServerResponse;
import com.nsi.dao.*;
import com.nsi.pojo.*;
import com.nsi.service.ICourseCategoryService;
import com.nsi.service.ICourseListService;
import com.nsi.service.IOrderService;
import com.nsi.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 订单业务层
 *
 * @author Luo Zhen
 * @create 2019-01-08 14:59
 */
@Service
@Slf4j
public class OrderServiceImpl implements IOrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private ShopGoodsMapper goodsMapper;
    @Autowired
    private ShopAddressMapper shopAddressMapper;
    @Autowired
    private ICourseListService iCourseListService;
    @Autowired
    private ICourseCategoryService iCourseCategoryService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ShopCartMapper shopCartMapper;

    @Override
    public ServerResponse createOrder(Order order) {
        if (isValidetOrder(order)) {
            return ServerResponse.createByErrorMessage("参数不合法");
        }
        // 购买类型是书店
        ShopGoods goods = goodsMapper.selectByPrimaryKey(order.getGoodsId());
        if (!Const.GoodsStatusEnum.PUT_AWAY.getValue().equals(goods.getGoodsState())) {
            return ServerResponse.createByErrorMessage("产品" + goods.getGoodsName() + "不是在线售卖状态");
        }

        // 地址Id不能为空
        if (order.getAddressId() == null) {
            return ServerResponse.createByErrorMessage("地址参数不合法");
        }
        int price = goods.getGoodsPrice();
        Order orderItem = createOrderByProductType(order, price);
        return ServerResponse.createBySuccess(orderItem);
    }

    @Override
    public int saveOrder(Order order) {
        return orderMapper.insert(order);
    }

    private Order createOrderByProductType(Order order, int totalPrice) {
        Order orderItem = new Order();
        orderItem.setOrderNo(generateOrderNo());
        orderItem.setWechatId(order.getWechatId());
        orderItem.setUnionId(order.getUnionId());
        orderItem.setGoodsId(order.getGoodsId());
        orderItem.setPayment(totalPrice);
        orderItem.setQuantity(order.getQuantity());
        orderItem.setTotalPrice(orderItem.getPayment() * order.getQuantity());
        orderItem.setStatus(Const.OrderStatusEnum.NO_PAY.getCode());
        orderItem.setProductType(order.getProductType());
        orderItem.setBuyerMessage(order.getBuyerMessage());
        orderItem.setAddressId(order.getAddressId());
        orderItem.setCreateTime(new Date());
        orderItem.setUpdateTime(orderItem.getCreateTime());

        this.saveOrder(orderItem);

        return orderItem;
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public ServerResponse createOrderByActivity(Order order) {
        Order orderItem = new Order();
        orderItem.setOrderNo(generateOrderNo());
        orderItem.setWechatId(order.getWechatId());
        orderItem.setGoodsId(order.getGoodsId());
        orderItem.setProductName(order.getProductName());
        orderItem.setProductType(order.getProductType());
        orderItem.setPayment(order.getPayment());
        orderItem.setQuantity(order.getQuantity());
        orderItem.setTotalPrice(order.getTotalPrice());
        orderItem.setStatus(Const.OrderStatusEnum.NO_PAY.getCode());
        orderItem.setBuyerMessage(order.getBuyerMessage());
        orderItem.setCreateTime(new Date());
        orderItem.setUpdateTime(orderItem.getCreateTime());

        this.saveOrder(orderItem);
        return ServerResponse.createBySuccess(orderItem);
    }

    @Override
    public void updateByOrderNo(String orderNo) {
        orderMapper.updateByOrderNo(orderNo, Const.OrderStatusEnum.PAID.getCode());
    }

    @Override
    public int findOrderNoAndStatus(String orderNo) {
        return orderMapper.findOrderNoAndStatus(orderNo);
    }

    // 封装购物车订单Vo
    private OrderListVo assembleOrderCartListVo(Order orderCartItem) {
        OrderListVo orderListVo = new OrderListVo();
        orderListVo.setOrderNo(orderCartItem.getOrderNo());

        orderListVo.setProductType(orderCartItem.getProductType());
        orderListVo.setShippingCode(orderCartItem.getShippingCode());
        orderListVo.setBuyerMessage(orderCartItem.getBuyerMessage());
        orderListVo.setPaymentTime(orderCartItem.getPaymentTime());

        orderListVo.setQuantity(orderCartItem.getQuantity());
        orderListVo.setTotal_price(orderCartItem.getTotalPrice());
        orderListVo.setStatus(orderCartItem.getStatus());
        orderListVo.setStatusDesc(Const.OrderStatusEnum.codeOf(orderCartItem.getStatus()).getValue());
        orderListVo.setCreateTime(orderCartItem.getCreateTime());
        orderListVo.setAddressId(orderCartItem.getAddressId());

        ShopGoods goods = new ShopGoods();
        goods.setId(orderCartItem.getGoodsId());

        orderListVo.setProduct(goods);
        return orderListVo;
    }

    @Override
    public ServerResponse createOrderByCourse(Order order, CourseList course) {
        if (Const.GoodsStatusEnum.PUT_AWAY.getValue().equals(course.getStatus())) {
            return ServerResponse.createByErrorMessage("课程" + course.getListTitle() + "已下架");
        }
        int price = course.getListPrice();
        Order orderItem = createOrderByProductType(order, price);
        return ServerResponse.createBySuccess(orderItem);
    }

    @Override
    public ServerResponse getOrderList(String wechatId, String unionId) {

        // 封装书籍订单
        List<Order> orderList = orderMapper.findOrderListByWechatId(wechatId, unionId, Const.ProductTypeEnum.BOOKSTORE.getValue());
        List<OrderListVo> orderListVoItem = new ArrayList<>();
        for (Order OrderGoodsItem : orderList) {
            OrderListVo orderListVo = assembleOrderListVo(OrderGoodsItem);
            orderListVoItem.add(orderListVo);
        }
        List<Order> orderCartList = orderMapper.findOrderListByWechatId(wechatId, unionId, Const.ProductTypeEnum.SHOPPING.getValue());
        for (Order orderCartItem : orderCartList) {
            OrderListVo orderCartVo = assembleOrderCartListVo(orderCartItem);
            orderListVoItem.add(orderCartVo);
        }

        if (CollectionUtils.isEmpty(orderListVoItem)) {
            return ServerResponse.createByErrorMessage("您还没有创建订单");
        }
        return ServerResponse.createBySuccess(orderListVoItem);
    }

    //    查询课程订单
    @Override
    public List<Order> findOrderList(String wechatId, String unionId, String productType) {
        return orderMapper.findOrderListByWechatId(wechatId, unionId, productType);
    }

    @Override
    public ServerResponse getOrderCourseList(List<Order> orderList) {
        List<OrderCourseListVo> orderCourseListVoItem = new ArrayList<>();
        for (Order orderCourseItem : orderList) {
            OrderCourseListVo orderCourseListVo = assembleOrderCourseListVo(orderCourseItem);
            orderCourseListVoItem.add(orderCourseListVo);
        }
        return ServerResponse.createBySuccess(orderCourseListVoItem);
    }

    // 封装课程订单Vo
    private OrderCourseListVo assembleOrderCourseListVo(Order order) {
        OrderCourseListVo orderCourseListVo = new OrderCourseListVo();
        orderCourseListVo.setOrderNo(order.getOrderNo());
        orderCourseListVo.setStatus(order.getStatus());
        orderCourseListVo.setStatusDesc(Const.OrderStatusEnum.codeOf(order.getStatus()).getValue());
        orderCourseListVo.setTotalPrice(order.getTotalPrice());

        CourseList course = iCourseListService.findCourseListById(order.getGoodsId());
        if (course != null) {
            orderCourseListVo.setListId(course.getListId());
            orderCourseListVo.setListTitle(course.getListTitle());
            orderCourseListVo.setListTheme(course.getListTheme());
            orderCourseListVo.setLecturer(course.getLecturer());
            orderCourseListVo.setListImgAddr(course.getListImg());
            orderCourseListVo.setSyllabus(course.getSyllabus());
        }
        return orderCourseListVo;
    }

    // 封装书籍订单Vo
    private OrderListVo assembleOrderListVo(Order order) {
        OrderListVo orderListVo = new OrderListVo();
        orderListVo.setOrderNo(order.getOrderNo());

        orderListVo.setProductType(order.getProductType());
        orderListVo.setShippingCode(order.getShippingCode());
        orderListVo.setBuyerMessage(order.getBuyerMessage());
        orderListVo.setPaymentTime(order.getPaymentTime());

        orderListVo.setQuantity(order.getQuantity());
        orderListVo.setTotal_price(order.getTotalPrice());
        orderListVo.setStatus(order.getStatus());
        orderListVo.setStatusDesc(Const.OrderStatusEnum.codeOf(order.getStatus()).getValue());
        orderListVo.setCreateTime(order.getCreateTime());
        orderListVo.setAddressId(order.getAddressId());

        ShopGoods goods = goodsMapper.selectByPrimaryKey(order.getGoodsId());
        if (goods != null) {
            orderListVo.setProduct(goods);
        }
        return orderListVo;
    }

    @Override
    public ServerResponse findOrderItemByOrderNo(String orderNo) {
        Order order = orderMapper.findOrderByOrderNo(orderNo);
        if (order != null) {
            OrderListVo orderListVo = assembleOrderListVo(order);
            return ServerResponse.createBySuccess(orderListVo);
        }
        return ServerResponse.createByErrorMessage("订单不存在");
    }

    @Override
    public ServerResponse cancelMe(String wechatId, String orderNo) {
        int count = orderMapper.updateByWechatIdAndOrderNo(wechatId, orderNo);
        if (count <= 0) {
            return ServerResponse.createByErrorMessage("订单修改状态失败");
        }
        return ServerResponse.createBySuccessMessage("订单修改状态成功");
    }

    @Override
    public ServerResponse findOrderByPage(int pageNum, int pageSize, String status, String productType, String searchKey) {
        PageHelper.startPage(pageNum, pageSize);
        List<Order> orderList = orderMapper.findOrderListByStatusAndType(status, productType, searchKey);
        List<OrderVo> orderVoList = new ArrayList<>();
        // 订单为空,查询不在
        if (CollectionUtils.isEmpty(orderList)) {
            PageInfo pageInfo = new PageInfo(orderList);
            return ServerResponse.createBySuccess(pageInfo);
        }
        for (Order item : orderList) {
            OrderVo orderVo = assembleOrderVo(item);
            orderVoList.add(orderVo);
        }
        PageInfo pageInfo = new PageInfo(orderList);
        pageInfo.setList(orderVoList);
        return ServerResponse.createBySuccess(pageInfo);
    }

    @Override
    public ServerResponse removeOrder(Long orderNo) {
        int count = orderMapper.deleteByOrderNo(orderNo);
        if (count <= 0) {
            return ServerResponse.createByErrorMessage("删除失败");
        }
        return ServerResponse.createBySuccess();
    }

    @Override
    public ServerResponse modifyOrder(Order order) {
        if (order.getOrderNo() == null) {
            return ServerResponse.createByErrorMessage("参数不合法");
        }
        int count = orderMapper.updateByOrderNoSelective(order);
        if (count <= 0) {
            return ServerResponse.createByErrorMessage("修改失败");
        }
        return ServerResponse.createBySuccessMessage("修改成功");
    }

    @Override
    public ServerResponse findOrderStatusCount(String wechatId, String unionId) {
        Map resultMap = new HashMap();
        int noPayCount = orderMapper.selectOneByWechatIdAndStatus(wechatId, unionId, Const.OrderStatusEnum.NO_PAY.getCode());
        int paidCount = orderMapper.selectOneByWechatIdAndStatus(wechatId, unionId, Const.OrderStatusEnum.PAID.getCode());
        int shippedCount = orderMapper.selectOneByWechatIdAndStatus(wechatId, unionId, Const.OrderStatusEnum.SHIPPED.getCode());

        resultMap.put("NO_PAY", noPayCount);
        resultMap.put("PAID", paidCount);
        resultMap.put("SHIPPED", shippedCount);
        return ServerResponse.createBySuccess(resultMap);
    }


    @Override
    public ServerResponse createOrderByShoppingCart(Order order) {
        //查询购物车
        ShopCart currentCart = shopCartMapper.selectByPrimaryKey(order.getGoodsId());
        if (currentCart == null) {
            return ServerResponse.createByErrorMessage("购物车不存在");
        }
        int totalPrice = Integer.parseInt(currentCart.getPrice());
        Order orderItem = this.createOrderByProductType(order, totalPrice);
        return ServerResponse.createBySuccess(orderItem);
    }

    @Override
    public Order findOrderstatusBywechatId(String wechatId) {
        return orderMapper.findOrderStatuswechatId(wechatId);
    }

    /**
     * 拼装所有订单
     *
     * @param order
     * @return
     */
    private OrderListVo assembleOrderListVos(Order order) {
        OrderListVo orderListVo = new OrderListVo();
        orderListVo.setOrderNo(order.getOrderNo());
        orderListVo.setProductType(order.getProductType());
        orderListVo.setShippingCode(order.getShippingCode());
        orderListVo.setBuyerMessage(order.getBuyerMessage());
        orderListVo.setPaymentTime(order.getPaymentTime());
        orderListVo.setQuantity(order.getQuantity());
        orderListVo.setTotal_price(order.getTotalPrice());
        orderListVo.setStatus(order.getStatus());
        orderListVo.setStatusDesc(Const.OrderStatusEnum.codeOf(order.getStatus()).getValue());
        orderListVo.setCreateTime(order.getCreateTime());

        if (order.getProductType().equals(Const.ProductTypeEnum.BOOKSTORE.getValue())) {
            ShopGoods goods = goodsMapper.selectByPrimaryKey(order.getGoodsId());
            orderListVo.setProduct(goods);
        }
        if (order.getProductType().equals(Const.ProductTypeEnum.MEETING.getValue())) {
            ShopGoods good = new ShopGoods();
            // 子课
            if (String.valueOf(order.getGoodsId()).length() > 4) {
                CourseCategory courseCategory = iCourseCategoryService.findCourseCategoryByCourseId(order.getGoodsId());
                good.setId(courseCategory.getCourseId());
                good.setGoodsName(courseCategory.getCourseName());
                orderListVo.setProduct(good);
                // 父课
            } else {
                CourseList course = iCourseListService.findCourseListById(order.getGoodsId());
                good.setId(course.getListId());
                good.setGoodsName(course.getListTitle());
                orderListVo.setProduct(good);
            }
        }
        if (order.getProductType().equals(Const.ProductTypeEnum.SHOPPING.getValue())) {
            ShopGoods good = new ShopGoods();
            good.setId(order.getGoodsId());
            orderListVo.setProduct(good);
        }

        return orderListVo;
    }


    @Override
    public ServerResponse getOrderByWechatIdAndUnionId(String wechatId, String unionId) {
        Order orderItem = orderMapper.getOrderByWechatIdAndUnionId(wechatId, unionId);
        if (orderItem == null) {
            return ServerResponse.createBySuccessMessage("您还没有添加购买的商品!");
        }
        OrderVo orderVo = this.assembleOrderVo(orderItem);
        return ServerResponse.createBySuccess(orderVo);
    }

    @Override
    public ServerResponse cancel(String wechatId, String unionId) {
        Order order = orderMapper.selectByWechatIdAndUnionId(wechatId, unionId);
        if (order == null) {
            return ServerResponse.createByErrorMessage("该用户订单不存在");
        }
        int count = orderMapper.updateByWechatId(wechatId, Const.OrderStatusEnum.CANCELED.getCode());
        if (count <= 0) {
            return ServerResponse.createByErrorMessage("取消订单失败");
        }
        return ServerResponse.createBySuccessMessage("取消订单成功");
    }

    /**
     * 封装订单Vo模型
     *
     * @param orderItem
     * @return
     */
    private OrderVo assembleOrderVo(Order orderItem) {
        OrderVo orderVo = new OrderVo();
        orderVo.setOrderNo(orderItem.getOrderNo());
        orderVo.setWechatId(orderItem.getWechatId());
        orderVo.setGoodsId(orderItem.getGoodsId());
        orderVo.setQuantity(orderItem.getQuantity());
        orderVo.setTotal_price(orderItem.getTotalPrice());
        orderVo.setStatus(orderItem.getStatus());
        orderVo.setProductName(orderItem.getProductName());
        orderVo.setStatusDesc(Const.OrderStatusEnum.codeOf(orderItem.getStatus()).getValue());
        orderVo.setCreateTime(orderItem.getCreateTime());
        orderVo.setProductType(orderItem.getProductType());
        orderVo.setBuyerMessage(orderItem.getBuyerMessage());
        orderVo.setShippingCode(orderItem.getShippingCode());
        orderVo.setPaymentTime(orderItem.getPaymentTime());
        orderVo.setAddressId(orderItem.getAddressId());

        // 判断购买类型
        if (Const.ProductTypeEnum.BOOKSTORE.getValue().equals(orderItem.getProductType())) {
            // 封装书店订单
            assembleGoodsOrder(orderVo, orderItem);
        } else if (Const.ProductTypeEnum.MEETING.getValue().equals(orderItem.getProductType())) {
            // 封装课程订单
            assembleCourseOrder(orderVo, orderItem);
        } else {
            // 封装购物车订单
            assembleCartOrder(orderVo, orderItem);
        }
        return orderVo;
    }

    /**
     * 组装课程订单
     *
     * @param orderVo
     * @param orderItem
     */
    private void assembleCourseOrder(OrderVo orderVo, Order orderItem) {
        ShopGoods goods = new ShopGoods();
        // 判断父类课程还是子类课程
        if (String.valueOf(orderItem.getGoodsId()).length() >= 4) {
            // 子课
            CourseCategory category = iCourseCategoryService.findCourseCategoryByCourseId(orderItem.getGoodsId());
            if (category != null) {
                goods.setId(category.getCourseId());
                goods.setGoodsName("单课——" + category.getCourseName());

                orderVo.setProduct(goods);
            }
        } else {
            // 父课
            CourseList course = iCourseListService.findCourseListById(orderItem.getGoodsId());
            if (course != null) {
                goods.setId(course.getListId());
                goods.setGoodsName("套课——" + course.getListTitle());

                orderVo.setProduct(goods);
            }
        }
        User user = userMapper.selectByWechatId(orderItem.getWechatId());
        if (user != null) {
            ShopVo shopVo = new ShopVo();
            shopVo.setUsermail(user.getUsername());
            shopVo.setReceivename(user.getUserTurename());
            shopVo.setReceivephone(user.getUserPhone());
            shopVo.setReceivearea01(user.getUserOrganization());

            orderVo.setShopVo(shopVo);
        }

    }

    /**
     * 组装书籍订单
     *
     * @param orderVo
     * @param orderItem
     */
    private void assembleGoodsOrder(OrderVo orderVo, Order orderItem) {
        ShopGoods goods = goodsMapper.selectByPrimaryKey(orderItem.getGoodsId());
        if (goods != null) {
            orderVo.setProduct(goods);
        }
        this.assembleCartOrder(orderVo, orderItem);
    }

    /**
     * 组装购物车订单
     *
     * @param orderVo
     * @param orderItem
     */
    private void assembleCartOrder(OrderVo orderVo, Order orderItem) {
        // 封装用户人信息
        ShopAddress address = shopAddressMapper.selectById(orderItem.getAddressId());
        if (address != null) {
            ShopVo shopVo = new ShopVo();
            shopVo.setUsermail(address.getUsermail());
            shopVo.setReceivename(address.getReceivename());
            shopVo.setReceivearea01(address.getReceivearea01());
            shopVo.setReceivearea02(address.getReceivearea02());
            shopVo.setReceivearea03(address.getReceivearea03());
            shopVo.setReceivephone(address.getReceivephone());
            shopVo.setPostcode(address.getPostcode());

            orderVo.setShopVo(shopVo);
        }
    }


    /**
     * 生成订单号方法
     *
     * @return
     */
    private long generateOrderNo() {
        long currentTime = System.currentTimeMillis();
        return currentTime + new Random().nextInt(100);
    }

    /**
     * 验证参数
     *
     * @param order
     * @return
     */
    private Boolean isValidetOrder(Order order) {
        if (order.getGoodsId() == null || order.getQuantity() == null || order.getQuantity() <= 0) {
            return true;
        }
        return false;
    }


}
